import { useState } from 'react'

function Demo3() {

  const [ goodsInfo, setGoodsInfo ] = useState({
    tabChannel: 0,
    arr1: [
      { goodsName: '电脑', stock: 100 },
      { goodsName: '手机', stock: 100 },
      { goodsName: '平板', stock: 100 }
    ],
    arr2: [
      { goodsName: 'xxx电脑', price: 8000 },
      { goodsName: 'yyy手机', price: 5000 },
      { goodsName: 'zzz平板', price: 3000 }
    ]
  })

  function handleChangeTab(num) {
    setGoodsInfo({
      ...goodsInfo,
      tabChannel: num
    })
  }

  function handleDelete(item) {
    console.log('item:', item)
    const _arr = goodsInfo.arr2.filter(v => v.goodsName != item.goodsName)
    setGoodsInfo({
      ...goodsInfo,
      arr2: _arr
    })
  }

  /**
   * 改变了tabChannel只有，自动就执行了这个函数。
   */
  function getContent() {
    console.log('getContent执行了吗？')
    if (goodsInfo.tabChannel == 1) {
      return goodsInfo.arr1.map((v, k) => (
        <div key={ k }>名称{ v.goodsName }，存量：{ v.stock }</div>
      ))
    } else if (goodsInfo.tabChannel == 2) {
      return goodsInfo.arr2.map((v, k) => (
        <div key={ k }>名称{ v.goodsName }，价格：{ v.price }，
          <button onClick={ () => handleDelete(v) }>删除</button>
        </div>
      ))
    } else {
      return <div>没有货物了</div>
    }
  }

  return (<>

    <div className="box-container">
      <div>tab: { goodsInfo.tabChannel }</div>
      <div className="tab-container">
        <div className="tab" onClick={ () => handleChangeTab(1) }>库存</div>
        <div className="tab" onClick={ () => handleChangeTab(2) }>商品</div>
      </div>

      <div>{ getContent() }</div>
    </div>
  </>)
}

export default Demo3
